// This is called for add input fields in webpage, not add to db
function add_source_item(anchor) {
    try {
        // find new item <li>
        var ul = $(anchor).parents('ul.source_detail').find("ul.new_items");
        $(ul).prepend($("#add_source_template").html());
        $(ul).find("li:first").hide();
        $(ul).find("li:first").slideDown('slow');

        // when title xpath input is changed and href xpath input is empty
        // automatically fill href xpath with the value of title xpath
        $(ul).find("li:first").find('input[name="title_xpath"]').change(
            function() {
                var href = $(this).parent().find('input[name="href_xpath"]');
                if ($(href).val() == "") {
                    $(href).val($(this).val());
                }
            }
        );
    } catch (err) {
        alert('got exception:' + err);
    }
}

// add or update one source item input
function update_source_item(anchor) {
    var root_div = $(anchor).parents('div.exist-source');

    var previous_max_item_id = 0;
    $(anchor).parents('ul.source_detail').find('input[name="item_id"]').each(
        function(index, input) {
            if ($(input).val() > previous_max_item_id) {
                previous_max_item_id = $(input).val();
            }
        });

    var source_id = $(anchor).parents('div.manage-source').find('input[name="source_id"]').val();
    $(anchor).parents('form.item-form').append(sprintf("<input type='hidden' name='source_id' value='%s'/>",
                                                       source_id));

    $(anchor).parents('form.item-form').submit(function() {
        var cur_form = $(this);
        $(root_div).find('span.update-status').html('PLEASE WAIT...').fadeIn('fast');
        $(this).ajaxSubmit({
            success: function(data) {
                $(root_div).load('sites-module/source-manage.php?type=edit&source_id=' + source_id,
                                 function() {
                                     $(root_div).find('a.toggle-basic-info').click();
                                     $(root_div).find('span.update-status').html(data).fadeIn('slow');
                                     var new_item_count = 0;
                                     $(root_div).find('form.item-form').each(function(index, form) {
                                         if ($(form).find('input[name="item_id"]').val() > previous_max_item_id) {
                                             $(form).addClass('new-item');
                                             new_item_count++;
                                         }
                                     });
                                 });

            },
            error: function(jqXHR, status) {
                alert('submit failed: ' + jqXHR.statusText);
            }
        });
        return false;
    }).submit();
}

function test_source_item(anchor){
    var form = $(anchor).parents('div.manage-source').find('form.ajax-sub');

    var url = $(form).find("input[name='base_url']").val();
    var keyword = $(form).find("input[name='keyword']").val();
    var encoding = $(form).find("input[name='encoding']").val();
    var need_query = ($(form).find("input[name='need_kw']").attr("checked") == 1);
    if (keyword == '' && need_query) {
        alert('请输入关键词');
        return false;
    }

    var detail_li = $(anchor).parents('li.item-detail');

    $(detail_li).find("img.loading").fadeIn('slow');
    var title_xpath = $(detail_li).find("input[name='title_xpath']").val();
    var content_xpath = $(detail_li).find("input[name='content_xpath']").val();
    var image_xpath = $(detail_li).find("input[name='image_xpath']").val();
    var href_xpath = $(detail_li).find("input[name='href_xpath']").val();


    if (url) {
        //   alert(sprintf(" url:%s\n keyword:%s\n encoding:%s\n need_query:%s\n \
        // title:%s\n content:%s\n image:%s\n href:%s\n",
        //                       url, keyword, encoding, need_query,
        //                       title_xpath, content_xpath, image_xpath, href_xpath
        //                      ));
        //   return;

        $.ajax({
            url: 'index.php?&op=test_item',
            type: 'POST',
            data: {url:url,
                   keyword:keyword,
                   encoding:encoding,
                   title_xpath:title_xpath,
                   content_xpath:content_xpath,
                   image_xpath:image_xpath,
                   href_xpath:href_xpath},
            success: function(data) {
                $(detail_li).find("img.loading").fadeOut('slow');
                try {
                    //alert(data); return;
                    var result = jQuery.parseJSON(data);
                    if (result.image == null || result.image.length == 0)
                        REDIPS.dialog.show(500, 400, result.tweet, 'OK');
                    else
                        REDIPS.dialog.show(500, 400, result.tweet + ', [图片:' + result.image + ']|' + result.image, 'OK');
                } catch(err) {
                    alert('Got unlucky error in JS:' + err + data);

                }
            },
            error: function(jqXHR, status) {
                alert('检测失败:' + status);
                $(detail_li).find("img.loading").fadeOut('slow');
            }
        });
    } else {
        alert('URL为空，无法测试');
    }
}

function look_form_rule(aobj,id){
    if(aobj.innerHTML == '+'){
        aobj.innerHTML = '-';
        $('#'+id).css('display','block');
    }else{
        aobj.innerHTML = '+';
        $('#'+id).css('display','none');
    }
}

function toggle_basic_info(anchor) {
    try {
        // figure out which to manipulate
        var target = $(anchor).parents('div.manage-source').find('ul.source_detail');
        var tree = $(anchor).parents('table').find('div.kw_tree');

        if (anchor.innerHTML == '+') {
            anchor.innerHTML = '－';
            //$(target).css('display', 'block');
            $(target).slideDown('slow', function() { 
                if ($(tree).html() == "") {
                    // load keyword tree
                    $(tree).jstree({
                        "core": {
                            "animation": 200
                        },

                        "xml_data": {
                            "ajax": { "url" : "../res/kwtree.xml",
                                    },
                            "xsl": "nest"
                        },

                        "themes": {
                            "theme": "apple"
                        },

                        plugins: ["xml_data", "themes"]
                    });
                } else {
                    $(tree).fadeIn('slow');
                }
            });

        } else {
            anchor.innerHTML = '+';
            $(target).slideUp('slow', function() {
                $(tree).fadeOut('slow');
            });
        }
    } catch (err) {
        alert('got exception: ' + err);
    }
}

// delete entire source
function remove_source(anchor, source_id_rep) {
    // get source id
    try {
        var sid = source_id_rep.replace(/_/g, '.');
        if (confirm('将要删除id为<' + sid + '>的源，是否继续?')) {
            $.post('index.php?op=delete_source',
                   {source_id: sid},
                   function(data) {
                       // data is json
                       var result = jQuery.parseJSON(data);
                       if (result.success == 'yes') {
                           $(anchor).parents('div.listing').slideUp(function() {
                               $(this).remove();
                           });
                       } else {
                           alert(sprintf('删除失败\nsql:(%s)\nerror:(%s)',
                                         result.sql, result.error));

                       }
                   });

        }
    } catch (err) {
        alert('get error:' + err);
    }
}


// delete one source item(associated with anchor)
function remove_source_item(anchor) {
    try {
        var li= $(anchor).parents("li.item-detail")
        var item_id = $(li).find("input[name='item_id']").val();

        if (item_id != '') {
            $.ajax({
                url: 'index.php?op=delete_item',
                data: {item_id: item_id},
                type: 'POST',
                success: function(data) {
                    if (data.indexOf('failed') == -1) {
                        $(li).slideUp('slow', function() {
                            $(li).remove();
                        });
                    } else {
                        alert(data);
                    }
                }
            });
        } else {
            $(li).slideUp('slow', function() {
                $(li).remove();
            });
        }
    } catch (err) {
        alert('删除失败了:' + err);
    }
}

// delete a source tag, identified by id
function remove_source_tag(del_link, id) {
    try {
        $("#"+id).remove();
        $(del_link).remove();
    } catch (err) {
        alert('got error:' + err);
    }
}

function add_source_tag_tree(anchor, new_tag) {
    try {
        var new_tag_id = "new_tag_" + (new Date().getTime());
        var new_html = sprintf('\
<a href="javascript:void(0)" onClick="remove_source_tag(this, \'%(id)s\')">(X)</a> \
<input type="text" class="source_tag" readonly="true" name="tags[]" value="%(value)s" id="%(id)s"/> \
', {id:new_tag_id, value:new_tag});

        // figure out container span
        var div = $(anchor).parents('table')[0];
        var span = $(div).find('span.source_tag_span');

        var duplicate = $(span).find(sprintf('input[type="text"][value="%s"]', new_tag))
        if ($(duplicate).size() > 0) {
            $(duplicate).each(function(index, item) {
                $(item).css('color', 'red');
                setTimeout(function() {
                    $(item).css('color', '#777');
                }, 8000);
            });
        } else {
            $(span).prepend(new_html);
            $("#"+new_tag_id).width(new_tag.length + 'em');
        }

    } catch (err) {
        alert('got error:' + err);
    }
}

// Initialization after page loading
$(document).ready(function() {
    try {
        // initialize dialog box
        REDIPS.dialog.init();
        REDIPS.dialog.op_high = 60;
        REDIPS.dialog.fade_speed = 18;

        // adjust source tag width
        $("span[id^='source_tag_span_']").each(function() {
            $(this).find('input').each(function() {
                $(this).width($(this).val().length + 2 + 'em');
            });
        });

        // load keyword tree
        $.jstree._themes = "jstree-themes/";

        $("div#kw_tree").bind("loaded.jstree", function(event, data) {

        }).jstree({
            "core": {
                "animation": 200
            },

            "xml_data": {
                "ajax": { "url" : "../res/kwtree.xml",
                          success: function() {
                          }
                        },
                "xsl": "nest"
            },

            "themes": {
                "theme": "apple"
            },

            plugins: ["xml_data", "themes"]
        });

        // Other init
        $("input[name='need_kw']").change(function(event) {
            if ($(event.target).attr('checked')) {
                $(event.target).parents('form').find('input[name="keyword"]').fadeIn('slow');
            } else {
                $(event.target).parents('form').find('input[name="keyword"]').fadeOut('slow');
            }
        });

        
        $("form.ajax-sub").submit(function() {
            var cur_form = $(this);
            var status = $(cur_form).parents('div.exist-source').find('span.update-status');
            $(status).html('PLEASE WAIT...').fadeIn('fast');
            $(this).ajaxSubmit({
                success: function(data) {
                    $(status).html(data)
                    setTimeout(
                        function() {
                            $(status).fadeOut('slow');
                        }, 10000);
                    
                },
                error: function(jqXHR, status) {
                    alert('submit failed: ' + jqXHR.statusText);
                }
            });
            return false;
        });
        
        $("form.add-source").find('a.toggle-basic-info').click();


    } catch(err) {
        alert('error on page loading: ' + err);
    }
});

